<template>
    <a-drawer
      :title="title"
      :maskClosable="true"
      :width="drawerWidth"
      placement="right"
      :closable="true"
      @close="handleCancel"
      :visible="visible"
      style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
      <a-form :form="form">
    <a-spin :spinning="confirmLoading">
      <a-button @click="setLightPhase" style="margin-right:10px" type="primary" icon="plus"> {{$t('light.writePhase')}} </a-button>
      <a-button @click="getLightPhase" style="margin-right:10px" type="primary" icon="plus"> {{$t('light.readPhase')}} </a-button>
      <a-button @click="copyLightPhase" style="margin-right:10px" type="primary" icon="plus"> {{$t('light.copyPhase')}} </a-button>
      <div style="margin-bottom:20px"></div>


      <div style="width: 170px;float: left;">
        <a-row  style="margin-bottom:10px" :gutter="16" v-for="(item, index) in phaseList1" :key="index">
          <a-col :span="1" style="width: 36px;padding-right:inherit;padding-left:8px;text-align: right;line-height: 30px;float: left;">
            {{index+1}}.
          </a-col>
          <a-col style="width: 150px;float: left;">
            <a-input maxlength="4" v-model="phaseList1[index]" />
          </a-col>
        </a-row>
      </div>

      <div style="width: 200px;float: left;">
        <a-row  style="margin-bottom:10px" :gutter="16" v-for="(item, index) in phaseList2" :key="index">
          <a-col style="width: 150px;">
            <a-input maxlength="4" v-model="phaseList2[index]" />
          </a-col>
        </a-row>
      </div>


    </a-spin>
      </a-form>
    </a-drawer>
</template>

<script>

  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import {duplicateCheck } from '@/api/api'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import Vue from 'vue'
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  export default {
    name: "GlrLightGateWayPhase",
    components: {
    },
    data () {
      return {
        form: this.$form.createForm(this),
        title: this.$t('light.phase') ,
        width:800,
        visible: false,
        drawerWidth:700,
        model: {},
        phaseList1:[],
        phaseList2:[],
        phaseListBak:"",
        headers: {},
        gateWayCode:'',
        disableMixinCreated:true,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        url: {
          add: "/glr/glrGateway/add",
          edit: "/glr/glrGateway/edit",
          readLightPhase:"/glr/glrGateway/readLightPhase",
          setLightPhase:"/glr/glrGateway/setLightPhase",
          importLightPhase: window._CONFIG['domianURL']+"/glr/glrGateway/importLightPhase?gateWayCode=",
        }
      }
    },
    computed: {
      importLightPhase: function () {
        return this.url.importLightPhase+this.gateWayCode;
      }
    },
    created () {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token": token};
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        const that = this;
        that.confirmLoading = true;
        that.phaseList1=[];
        that.phaseList2=[];
        that.phaseListBak="";
        this.visible = true;
        this.gateWayCode=record.gateWayCode;
        let httpurl =this.url.readLightPhase;
        httpAction(httpurl,{gateWayCode:record.gateWayCode},"post").then((res)=>{
          if(res.success){
            that.phaseList1=res.result.data.v1;
            console.info(that.phaseList1);
            that.phaseList2=res.result.data.v2;
            console.info(that.phaseList2);
            //that.$message.success(res.message);
            that.$message.success(that.$t('base.operationSuccessful'));
            that.$emit('ok');
          }else{
            //that.$message.warning(res.message);
                      that.$message.warning(that.$t('base.operationFailed'));
          }
        }).finally(() => {
          that.confirmLoading = false;
        })


      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl =this.url.readLightPhase;
            httpAction(httpurl,formData,"post").then((res)=>{
              if(res.success){
                //that.$message.success(res.message);
                that.$message.success(that.$t('base.operationSuccessful'));
                that.$emit('ok');
              }else{
                //that.$message.warning(res.message);
                      that.$message.warning(that.$t('base.operationFailed'));
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }

        })
      },
      fanzhuan(array){
        var temp = [];
        for(var i=array.length-1;i>=0;i--){
          temp[temp.length]=array[i];
        }
        for(var j=0;j<temp.length;j++){
          array[j]=temp[j];
        }
        return array;
      },
      isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == ""){
          return true;
        }else{
          return false;
        }
      },
      deEmptyData(phaseListData){
        //phaseList2bak:"",
        this.phaseListBak="";
        this.phaseListBak = phaseListData.join(',');

        var  arr=phaseListData;
        arr=this.fanzhuan(arr);

        var temp = [];
        var bFirst=false; //找到第一个非空的标志
        for(var j=0;j<arr.length;j++){
          if (!this.isEmpty(arr[j])) {
            temp[temp.length]=arr[j];
            bFirst=true;
          }else{
            if (bFirst){
              temp[temp.length]=arr[j];
            }
          }
        }
        temp=this.fanzhuan(temp);

        return temp.join(",")
      },
      setLightPhase(){
        const that = this;

        var phaseList1New=this.deEmptyData(this.phaseList1);
        var arr1 = this.phaseListBak.split(',');
        this.phaseList1=arr1;

        var phaseList2New=this.deEmptyData(this.phaseList2);
        var arr2 = this.phaseListBak.split(',');
        this.phaseList2=arr2;

        this.$confirm({
          title: this.$t('base.confirm'),
          content: this.$t('light.confirmCopyPhase') ,
          onOk: function () {
            that.loading = true;
            that.confirmLoading = true;
            let httpurl =that.url.setLightPhase;
            httpAction(httpurl,{gateWayCode:that.gateWayCode,v1:phaseList1New,v2:phaseList2New},"post").then((res)=>{
              if(res.success){
                //that.$message.success(res.message);
                that.$message.success(that.$t('base.operationSuccessful'));
                //that.$emit('ok');
              }else{
                //that.$message.warning(res.message);
                      that.$message.warning(that.$t('base.operationFailed'));
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      copyLightPhase(){
        this.phaseList1=[].concat(this.phaseList2);
      },
      getLightPhase(){
        const that = this;
        that.confirmLoading = true;
        this.visible = true;
        that.phaseList1=[];
        that.phaseList2=[];
        that.phaseListBak="";
        let httpurl =this.url.readLightPhase;
        httpAction(httpurl,{gateWayCode:this.gateWayCode},"post").then((res)=>{
          if(res.success){
            that.phaseList1=res.result.data.v1;
            console.info(that.phaseList1);
            //that.$message.success(res.message);
            that.$message.success(that.$t('base.operationSuccessful'));
            that.$emit('ok');
          }else{
            //that.$message.warning(res.message);
                      that.$message.warning(that.$t('base.operationFailed'));
          }
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
      handleCancel () {
        this.close()
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'currentWorkStatus','phoneNumber','phoneType','gatewayModel','gatewayType','longitude','latitude','gatewayName','gateWayCode','sysCompanyCode','controlNumber','controlModel','currentPeriod','dimmingValue','switchingState','temperature','humidity','voltageA','voltageB','voltageC','currentA','currentB','currentC','illuminance','outage','signalValue','cellVoltage'))
      },
      /* 导入 */
      handleImportExcelLightPhase(info){
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            // this.$message.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let { message, result: { msg, fileUrl, fileName } } = info.file.response
              let href = window._CONFIG['domianURL'] + fileUrl
              this.$message.error(`操作失败: ${info.file.msg} `);
            } else {
              this.$message.success(info.file.response.message || `${info.file.name} 操作成功`)
            }
            this.loadData()
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`操作失败: ${info.file.msg} `);
        }
      },

    }
  }
</script>

<style scoped>

</style>